var sio = require('socket.io');
var onlineCount = 0;
var sockets = {};
var currentRoomName = 'myroom';
var currentRoom = {};
// var nicknames = new Array();
var currentNickname = null;
var Chat = function(server) {
    this.io = new sio(server);
    this.io.on('connection', function(socket) {
        //将当前socket加入房间中
        joinRoom(socket, currentRoomName);
        //将当前socket连接加入对象属性中
        sockets[socket.id] = {};
        sockets[socket.id].socket = socket;
        currentRoom = sockets[socket.id].socket.adapter.rooms[currentRoomName];
        //计算当前房间的人数
        var currentRoomTotal = calculateOnlineCountInRoom(currentRoom);

        //更新总人数
        socket.emit('onlineCount', {
            'onlineCount': currentRoomTotal
        });
        handleMessageBroadcast(socket, currentRoom, 'onlineCount', {
            'onlineCount': currentRoomTotal
        });

        socket.on('my other event', function(data) {
            console.log(data);
        });
        socket.once('init', function(data) {
            //将已存在的用户名保存到对象中
            currentNickname = data.nickname;
            //查找当前用户名是否已存在
            var isExist = checkExist(currentNickname, sockets, 'nickname');
            if (!isExist) {
                sockets[socket.id].nickname = currentNickname;
            }
            //发送欢迎通知到当前客户端
            socket.emit('system', {
                msg: "欢迎加入!",
            });
            //发送消息通知加入新用户
            handleMessageBroadcast(socket, currentRoom, 'system', {
                msg: "用户" + sockets[socket.id].nickname + "加入了房间",
            });

        });

        socket.on('message', function(data) {
            console.log('form server:' + data);
            //转发接收到的消息给房间内的其他人
            handleMessageBroadcast(socket, currentRoom, 'news', data);
        });
        socket.on('disconnect', function() {
            handleDisconnect(socket, currentRoom, currentRoomName);
        });
    });

};

function joinRoom(socket, room) {
    socket.join(room);
}

function handleDisconnect(socket, currentRoom, currentRoomName) {
    //发送退出消息给房间内的人
    handleMessageBroadcast(socket, currentRoom, 'system', {
        msg: "用户" + sockets[socket.id].nickname + "离开了房间",
        nickname: 'system'
    });
    socket.leave(currentRoomName);
    //计算当前房间的人数
    var currentRoomTotal = calculateOnlineCountInRoom(currentRoom);
    //更新人数，并发送消息
    onlineCount = currentRoomTotal;
    handleMessageBroadcast(socket, currentRoom, 'onlineCount', {
        'onlineCount': onlineCount
    });
    //更新已连接的sockets
    for (var s in sockets) {
        var isExist = checkExist(s, currentRoom.sockets);
        if (!isExist) {
            delete sockets[s];
        }
    }
}

function calculateOnlineCountInRoom(room) {
    var total = 0;
    if (room) {
        for (var i in room.sockets) {
            total++;
        }
    }
    //todo 显示所有
    return total;
}

function handleMessageBroadcast(socket, currentRoom, eventProxy, data) {
    for (var id in currentRoom.sockets) {
        socket.broadcast.to(id).emit(eventProxy, data);
    }
}

function checkExist(str, object, element) {
    var isExist = false;
    for (var i in object) {
        var current = null;
        if (element) {
            current = i[element];
        } else {
            current = i;
        }
        if (current == str) {
            isExist = true;
            break;
        }
    }
    return isExist;
}
module.exports = Chat;